<template>
	<view class="ai-chat-container">
		<!-- 顶部导航栏 -->
		<view class="chat-header">
			<view class="header-left" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="header-center" @click="showConversationList">
				<text class="chat-title">{{ currentConversationTitle || 'AI助手' }}</text>
				<text class="chat-subtitle" v-if="currentConversationTitle">点击切换会话</text>
			</view>
			<view class="header-right">
				<text class="menu-icon" @click="showMenu">⋯</text>
			</view>
		</view>

		<!-- 消息列表 -->
		<scroll-view
			class="message-list"
			scroll-y
			:scroll-top="scrollTop"
			:scroll-into-view="scrollIntoView"
			@scrolltoupper="loadMoreHistory"
			:refresher-enabled="true"
			:refresher-triggered="isLoadingHistory"
			@refresherrefresh="refreshChatHistory"
		>
			<view class="message-container">
				<!-- 欢迎消息 -->
				<view v-if="validMessages.length === 0" class="welcome-message">
					<view class="ai-avatar">
						<text class="ai-icon">AI</text>
					</view>
					<view class="welcome-text">
						<text class="welcome-title">你好！我是您的专属客服</text>
						<text class="welcome-desc">有什么可以帮助您的吗？</text>
					</view>
				</view>

				<!-- 消息列表 -->
				<view
					v-for="(message, index) in validMessages"
					:key="message.id"
					:id="'msg-' + index"
					class="message-item"
					:class="{ 'user-message': message.isUser, 'ai-message': !message.isUser }"
				>
					<!-- AI消息布局 -->
					<template v-if="!message.isUser">
						<view class="message-content">
							<view class="ai-avatar">
								<text class="ai-icon">AI</text>
							</view>
							<view class="message-wrapper">
								<view class="message-bubble ai-bubble">
									<text class="message-text">{{ message.content }}</text>
								</view>
								<view class="message-time">
									<text class="time-text">{{ formatTime(message.timestamp) }}</text>
								</view>
							</view>
						</view>
					</template>

					<!-- 用户消息布局 -->
					<template v-else>
						<view class="self-message-container">
							<view class="message-wrapper">
								<view class="message-bubble user-bubble">
									<text class="message-text">{{ message.content }}</text>
								</view>
								<view class="message-time">
									<text class="time-text">{{ formatTime(message.timestamp) }}</text>
								</view>
							</view>
							<view class="user-avatar">
								<image class="avatar-img" :src="userAvatar" mode="aspectFill" />
							</view>
						</view>
					</template>
				</view>

				<!-- 加载中提示 -->
				<view v-if="isAiTyping" class="message-item ai-message">
					<view class="message-content">
						<view class="ai-avatar">
							<text class="ai-icon">AI</text>
						</view>
						<view class="message-wrapper">
							<view class="message-bubble ai-bubble typing">
								<view class="typing-indicator">
									<view class="dot"></view>
									<view class="dot"></view>
									<view class="dot"></view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 输入区域 -->
		<view class="input-area">
			<view class="input-container">
				<textarea 
					v-model="inputText"
					class="message-input"
					placeholder="输入消息..."
					:auto-height="true"
					:maxlength="1000"
					@input="onInput"
					@confirm="sendMessage"
				/>
				<view 
					class="send-btn" 
					:class="{ 'active': canSend }"
					@click="sendMessage"
				>
					<text class="send-text">发送</text>
				</view>
			</view>
		</view>

		<!-- 菜单弹窗 -->
		<view v-if="showMenuModal" class="menu-modal" @click="showMenuModal = false">
			<view class="menu-content" @click.stop>
				<view class="menu-option" @click="showConversationList">
					<text class="option-text">会话列表</text>
				</view>
				<view class="menu-option" @click="newChat">
					<text class="option-text">新建对话</text>
				</view>
				<view class="menu-option" @click="renameConversation">
					<text class="option-text">重命名会话</text>
				</view>
				<view class="menu-option" @click="clearChat">
					<text class="option-text">清空对话</text>
				</view>
				<view class="menu-option" @click="exportChatHistory">
					<text class="option-text">导出聊天记录</text>
				</view>
				<view class="menu-option" @click="transferToHuman">
					<text class="option-text">转人工客服</text>
				</view>
				<view class="menu-option" @click="deleteCurrentConversation" style="color: #ff4757;">
					<text class="option-text">删除会话</text>
				</view>
			</view>
		</view>

		<!-- 会话列表弹窗 -->
		<view v-if="showConversationListModal" class="conversation-list-modal" @click="showConversationListModal = false">
			<view class="conversation-list-content" @click.stop>
				<view class="conversation-list-header">
					<text class="list-title">会话列表</text>
					<text class="close-btn" @click="showConversationListModal = false">×</text>
				</view>
				<scroll-view class="conversation-list-scroll" scroll-y>
					<view class="conversation-item"
						  v-for="conversation in conversationList"
						  :key="conversation.conversationId"
						  :class="{ 'active': conversation.conversationId === conversationId }"
						  @click="switchConversation(conversation)">
						<view class="conversation-info">
							<text class="conversation-title">{{ conversation.title }}</text>
							<text class="conversation-time">{{ formatTime(conversation.lastMessageTime) }}</text>
						</view>
						<view class="conversation-preview">
							<text class="preview-text">{{ conversation.lastMessage || '暂无消息' }}</text>
						</view>
					</view>
					<view v-if="conversationList.length === 0" class="empty-conversations">
						<text class="empty-text">暂无会话记录</text>
					</view>
				</scroll-view>
				<view class="conversation-list-footer">
					<button class="new-conversation-btn" @click="newChat">新建会话</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import aiApi from '../../api/ai.js'
import { resolveAvatarUrl } from '../../utils/avatar.js'

// 响应式数据
const messages = ref([])
const inputText = ref('')
const isAiTyping = ref(false)
const scrollTop = ref(0)
const scrollIntoView = ref('')
const showMenuModal = ref(false)
const showConversationListModal = ref(false)
const conversationId = ref('')
const currentConversationTitle = ref('')
const conversationList = ref([])
const isLoadingConversations = ref(false)
const isLoadingHistory = ref(false)
const hasMoreHistory = ref(true)
const currentHistoryPage = ref(1)

// 用户信息
const userInfo = uni.getStorageSync('userInfo') || {}
const userAvatar = ref(resolveAvatarUrl(userInfo.avatar || ''))
const userId = userInfo.id || userInfo.userId

// 计算属性
const canSend = computed(() => {
	return inputText.value.trim().length > 0 && !isAiTyping.value
})

// 过滤有效消息
const validMessages = computed(() => {
	return messages.value.filter(message =>
		message &&
		message.content &&
		typeof message.content === 'string' &&
		message.content.trim().length > 0
	)
})

// 页面生命周期
onMounted(async () => {
	// 检查用户登录状态
	if (!userId) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
		return
	}

	// 可以从路由参数获取会话ID
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	if (currentPage.options.conversationId) {
		conversationId.value = currentPage.options.conversationId
		await loadConversationDetails()
		await loadChatHistory()
	} else {
		// 加载用户的会话列表
		await loadConversationList()

		// 如果没有现有会话，创建一个新会话
		if (conversationList.value.length === 0) {
			await createNewConversation()
		} else {
			// 使用最近的会话
			const latestConversation = conversationList.value[0]
			conversationId.value = latestConversation.conversationId
			currentConversationTitle.value = latestConversation.title

			// 加载聊天历史
			await loadChatHistory()
		}
	}

	// 滚动到底部
	nextTick(() => {
		scrollToBottom()
	})
})

// 加载聊天历史
const loadChatHistory = async (reset = true) => {
	if (!conversationId.value || !userId) return

	if (reset) {
		currentHistoryPage.value = 1
		hasMoreHistory.value = true
		messages.value = []
	}

	if (!hasMoreHistory.value) return

	isLoadingHistory.value = true

	try {
		const response = await aiApi.getChatHistory({
			conversationId: conversationId.value,
			userId: userId,
			page: currentHistoryPage.value,
			size: 20,
			descending: false
		})

		if (response && response.success && response.data) {
			const newMessages = response.data.map(msg => ({
				id: msg.id || Date.now() + Math.random(),
				content: msg.content,
				isUser: msg.messageType === 'USER',
				timestamp: msg.timestamp || Date.now()
			}))

			if (reset) {
				messages.value = newMessages
			} else {
				// 加载更多时，将新消息添加到开头
				messages.value = [...newMessages, ...messages.value]
			}

			// 检查是否还有更多数据
			hasMoreHistory.value = response.data.length === 20

			if (reset) {
				scrollToBottom()
			}
		}
	} catch (error) {
		console.error('加载聊天历史失败:', error)
	} finally {
		isLoadingHistory.value = false
	}
}

// 加载更多历史记录
const loadMoreHistory = async () => {
	if (isLoadingHistory.value || !hasMoreHistory.value) return

	currentHistoryPage.value++
	await loadChatHistory(false)
}

// 刷新聊天历史
const refreshChatHistory = async () => {
	await loadChatHistory(true)
}

// 发送消息
const sendMessage = async () => {
	if (!canSend.value) return
	
	const messageText = inputText.value.trim()
	if (!messageText) return
	
	// 添加用户消息
	const userMessage = {
		id: Date.now() + Math.random(),
		content: messageText,
		isUser: true,
		timestamp: Date.now()
	}
	messages.value.push(userMessage)
	inputText.value = ''
	
	// 滚动到底部
	scrollToBottom()
	
	// 显示AI正在输入
	isAiTyping.value = true
	scrollToBottom()

	try {
		// 确保有会话ID
		if (!conversationId.value) {
			await createNewConversation()
		}

		// 调用AI接口（流式响应）
		const response = await aiApi.sendMessage({
			question: messageText,
			memoryId: conversationId.value,
			userId: userId
		})

		// 处理响应内容
		let responseContent = ''
		if (response && typeof response === 'string' && response.trim()) {
			responseContent = response.trim()
		} else {
			responseContent = '抱歉，我现在无法回复。'
		}

		// 只有在有实际内容时才创建AI消息
		if (responseContent) {
			const aiMessage = {
				id: Date.now() + Math.random(),
				content: responseContent,
				isUser: false,
				timestamp: Date.now()
			}
			messages.value.push(aiMessage)
		}

	} catch (error) {
		console.error('发送消息失败:', error)

		// 创建错误消息
		const errorMessage = {
			id: Date.now() + Math.random(),
			content: '抱歉，消息发送失败，请稍后重试。',
			isUser: false,
			timestamp: Date.now()
		}
		messages.value.push(errorMessage)

		uni.showToast({
			title: '发送失败',
			icon: 'none'
		})
	} finally {
		isAiTyping.value = false
		scrollToBottom()
	}
}

// 滚动到底部
const scrollToBottom = () => {
	nextTick(() => {
		if (validMessages.value.length > 0) {
			scrollIntoView.value = 'msg-' + (validMessages.value.length - 1)
		}
	})
}

// 输入事件
const onInput = (e) => {
	inputText.value = e.detail.value
}

// 格式化时间
const formatTime = (timestamp) => {
	const date = new Date(timestamp)
	return date.toLocaleTimeString('zh-CN', { 
		hour: '2-digit', 
		minute: '2-digit' 
	})
}

// 返回
const goBack = () => {
	uni.navigateBack()
}

// 显示菜单
const showMenu = () => {
	showMenuModal.value = true
}

// 清空对话
const clearChat = () => {
	uni.showModal({
		title: '清空对话',
		content: '确定要清空当前对话吗？',
		success: (res) => {
			if (res.confirm) {
				messages.value = []
				showMenuModal.value = false
				uni.showToast({
					title: '已清空',
					icon: 'success'
				})
			}
		}
	})
}

// 新建对话
const newChat = async () => {
	showMenuModal.value = false
	showConversationListModal.value = false

	try {
		await createNewConversation()
		uni.showToast({
			title: '新对话已创建',
			icon: 'success'
		})
	} catch (error) {
		console.error('创建新对话失败:', error)
		uni.showToast({
			title: '创建失败',
			icon: 'none'
		})
	}
}

// 导出聊天记录
const exportChatHistory = async () => {
	showMenuModal.value = false

	if (messages.value.length === 0) {
		uni.showToast({
			title: '暂无聊天记录',
			icon: 'none'
		})
		return
	}

	try {
		// 生成聊天记录文本
		const chatText = generateChatText()

		// 在小程序中，可以将文本复制到剪贴板
		uni.setClipboardData({
			data: chatText,
			success: () => {
				uni.showToast({
					title: '聊天记录已复制到剪贴板',
					icon: 'success'
				})
			},
			fail: () => {
				uni.showToast({
					title: '导出失败',
					icon: 'none'
				})
			}
		})
	} catch (error) {
		console.error('导出聊天记录失败:', error)
		uni.showToast({
			title: '导出失败',
			icon: 'none'
		})
	}
}

// 生成聊天记录文本
const generateChatText = () => {
	const title = `${currentConversationTitle.value || 'AI对话'} - 聊天记录`
	const exportTime = new Date().toLocaleString('zh-CN')

	let chatText = `${title}\n导出时间: ${exportTime}\n\n`

	messages.value.forEach((message, index) => {
		const time = formatTime(message.timestamp)
		const sender = message.isUser ? '我' : 'AI助手'
		chatText += `[${time}] ${sender}: ${message.content}\n\n`
	})

	return chatText
}

// 搜索聊天记录
const searchInHistory = (keyword) => {
	if (!keyword || keyword.trim() === '') {
		return messages.value
	}

	return messages.value.filter(message =>
		message.content && message.content.toLowerCase().includes(keyword.toLowerCase())
	)
}

// 统计聊天数据
const getChatStatistics = () => {
	const totalMessages = messages.value.length
	const userMessages = messages.value.filter(msg => msg.isUser).length
	const aiMessages = messages.value.filter(msg => !msg.isUser).length

	return {
		total: totalMessages,
		user: userMessages,
		ai: aiMessages,
		conversationTitle: currentConversationTitle.value
	}
}

// 转人工客服
const transferToHuman = async () => {
	showMenuModal.value = false

	if (!userId) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}

	uni.showModal({
		title: '转人工客服',
		content: '确定要转接人工客服吗？我们将为您联系专业的客服人员。',
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '正在转接...'
					})

					const response = await aiApi.transferToHuman({
						userId: userId,
						conversationId: conversationId.value,
						message: '用户通过菜单请求转人工客服'
					})

					uni.hideLoading()

					if (response && response.success) {
						// 获取客服信息
						const customerService = response.customerService

						if (customerService) {
							// 构建跳转到聊天页面的URL，携带客服信息
							const chatUrl = `/pages/message/chat?type=private&name=${encodeURIComponent(customerService.nickname || '人工客服')}&nickname=${encodeURIComponent(customerService.nickname || '人工客服')}&avatar=${encodeURIComponent(customerService.avatar || '')}&toUserId=${customerService.id}&isCustomerService=true`

							// 跳转到聊天页面
							uni.navigateTo({
								url: chatUrl,
								success: () => {
									uni.showToast({
										title: '转接成功',
										icon: 'success'
									})
								},
								fail: (error) => {
									console.error('跳转聊天页面失败:', error)
									uni.showToast({
										title: '跳转失败，请重试',
										icon: 'none'
									})
								}
							})
						} else {
							// 如果没有客服信息，显示错误消息
							uni.showToast({
								title: '获取客服信息失败',
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: response.message || '转接失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('转人工失败:', error)
					uni.showToast({
						title: '转接失败，请稍后再试',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 创建新会话
const createNewConversation = async () => {
	if (!userId) return

	try {
		const response = await aiApi.createConversation({
			userId: userId,
			title: `新对话 ${new Date().toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })}`
		})

		if (response && response.success && response.data) {
			conversationId.value = response.data.conversationId
			currentConversationTitle.value = response.data.title
			messages.value = []

			// 刷新会话列表
			await loadConversationList()
		}
	} catch (error) {
		console.error('创建新会话失败:', error)
		throw error
	}
}

// 加载会话列表
const loadConversationList = async () => {
	if (!userId) return

	isLoadingConversations.value = true
	try {
		const response = await aiApi.getConversations({
			userId: userId,
			page: 1,
			size: 50,
			includeArchived: false
		})

		if (response && response.success && response.data) {
			conversationList.value = response.data
		}
	} catch (error) {
		console.error('加载会话列表失败:', error)
	} finally {
		isLoadingConversations.value = false
	}
}

// 加载会话详情
const loadConversationDetails = async () => {
	if (!conversationId.value || !userId) return

	try {
		const response = await aiApi.getConversation(conversationId.value, userId)

		if (response && response.success && response.data) {
			currentConversationTitle.value = response.data.title
		}
	} catch (error) {
		console.error('加载会话详情失败:', error)
	}
}

// 显示会话列表
const showConversationList = async () => {
	showMenuModal.value = false
	await loadConversationList()
	showConversationListModal.value = true
}

// 切换会话
const switchConversation = async (conversation) => {
	showConversationListModal.value = false

	if (conversation.conversationId === conversationId.value) {
		return
	}

	conversationId.value = conversation.conversationId
	currentConversationTitle.value = conversation.title
	messages.value = []

	// 加载新会话的聊天历史
	await loadChatHistory()

	uni.showToast({
		title: '已切换会话',
		icon: 'success'
	})
}

// 重命名会话
const renameConversation = () => {
	showMenuModal.value = false

	uni.showModal({
		title: '重命名会话',
		editable: true,
		placeholderText: currentConversationTitle.value,
		success: async (res) => {
			if (res.confirm && res.content && res.content.trim()) {
				try {
					const response = await aiApi.updateConversationTitle(
						conversationId.value,
						userId,
						res.content.trim()
					)

					if (response && response.success) {
						currentConversationTitle.value = res.content.trim()
						await loadConversationList()
						uni.showToast({
							title: '重命名成功',
							icon: 'success'
						})
					}
				} catch (error) {
					console.error('重命名失败:', error)
					uni.showToast({
						title: '重命名失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 删除当前会话
const deleteCurrentConversation = () => {
	showMenuModal.value = false

	uni.showModal({
		title: '删除会话',
		content: '确定要删除当前会话吗？删除后无法恢复。',
		success: async (res) => {
			if (res.confirm) {
				try {
					const response = await aiApi.deleteConversation(conversationId.value, userId)

					if (response && response.success) {
						// 刷新会话列表
						await loadConversationList()

						// 如果还有其他会话，切换到最新的会话
						if (conversationList.value.length > 0) {
							const latestConversation = conversationList.value[0]
							conversationId.value = latestConversation.conversationId
							currentConversationTitle.value = latestConversation.title
							messages.value = []
							await loadChatHistory()
						} else {
							// 如果没有其他会话，创建新会话
							await createNewConversation()
						}

						uni.showToast({
							title: '会话已删除',
							icon: 'success'
						})
					}
				} catch (error) {
					console.error('删除会话失败:', error)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.ai-chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #F5F5F5;
}

.chat-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10px 15px;
	background: #FFFFFF;
	border-bottom: 1px solid #E5E5E5;
	
	.header-left, .header-right {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.back-icon, .menu-icon {
		font-size: 18px;
		color: #333333;
	}
	
	.header-center {
		flex: 1;
		text-align: center;
		cursor: pointer;
	}

	.chat-title {
		font-size: 18px;
		font-weight: 600;
		color: #333333;
	}

	.chat-subtitle {
		font-size: 12px;
		color: #999999;
		margin-top: 2px;
	}
}

.message-list {
	flex: 1;
	padding: 10px 0;
}

.message-container {
	padding: 0 15px;

	/* 小屏幕优化 */
	@media (max-width: 480px) {
		padding: 0 10px;

		.message-wrapper {
			max-width: 85%;
		}
	}

	/* 针对短消息的优化 */
	.message-bubble {
		min-width: fit-content; /* 让短消息紧凑显示 */
	}
}

.welcome-message {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20px;
	
	.ai-avatar {
		width: 40px;
		height: 40px;
		border-radius: 20px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 10px;
		
		.ai-icon {
			color: #FFFFFF;
			font-size: 14px;
			font-weight: 600;
		}
	}
	
	.welcome-text {
		flex: 1;
		
		.welcome-title {
			display: block;
			font-size: 16px;
			font-weight: 600;
			color: #333333;
			margin-bottom: 5px;
		}
		
		.welcome-desc {
			display: block;
			font-size: 14px;
			color: #666666;
		}
	}
}

.message-item {
	margin-bottom: 12px; /* 减少消息间距 */
	width: 100%;
}

.message-content {
	display: flex;
	align-items: flex-start; /* 改为顶部对齐 */
	gap: 10px; /* 稍微增加间距 */
	width: 100%;
}

.self-message-container {
	display: flex;
	align-items: flex-start; /* 改为顶部对齐 */
	gap: 10px; /* 稍微增加间距 */
	width: 100%;
	justify-content: flex-end;
}

.message-wrapper {
	display: flex;
	flex-direction: column;
	max-width: 80%; /* 增加最大宽度 */
	min-width: 0; /* 允许收缩 */
}

.ai-avatar {
	width: 40px;
	height: 40px;
	border-radius: 20px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;

	.ai-icon {
		color: #FFFFFF;
		font-size: 14px;
		font-weight: 600;
	}
}

.user-avatar {
	width: 40px;
	height: 40px;
	flex-shrink: 0;

	.avatar-img {
		width: 100%;
		height: 100%;
		border-radius: 20px;
	}
}

.message-bubble {
	padding: 10px 14px; /* 减少内边距 */
	border-radius: 18px;
	margin-bottom: 3px; /* 减少与时间的间距 */
	word-wrap: break-word;
	word-break: break-word;
	display: inline-block; /* 让气泡根据内容自适应宽度 */
	max-width: 100%;

	&.user-bubble {
		background: #007AFF;

		.message-text {
			color: #FFFFFF;
		}
	}

	&.ai-bubble {
		background: #FFFFFF;
		border: 1px solid #E5E5E5;

		.message-text {
			color: #333333;
		}

		&.typing {
			padding: 16px;
		}
	}
}

.message-text {
	font-size: 16px;
	line-height: 1.4;
	word-wrap: break-word;
	white-space: pre-wrap; /* 保持空格和换行 */
	display: inline; /* 让文本内联显示 */
}

.message-time {
	.time-text {
		font-size: 12px;
		color: #999999;
		display: block;
	}
}

/* AI消息时间左对齐 */
.message-content .message-time {
	text-align: left;
}

/* 用户消息时间右对齐 */
.self-message-container .message-time {
	text-align: right;
}

.typing-indicator {
	display: flex;
	align-items: center;
	gap: 4px;
	
	.dot {
		width: 6px;
		height: 6px;
		border-radius: 50%;
		background: #999999;
		animation: typing 1.4s infinite ease-in-out;
		
		&:nth-child(1) { animation-delay: -0.32s; }
		&:nth-child(2) { animation-delay: -0.16s; }
		&:nth-child(3) { animation-delay: 0s; }
	}
}

@keyframes typing {
	0%, 80%, 100% {
		transform: scale(0.8);
		opacity: 0.5;
	}
	40% {
		transform: scale(1);
		opacity: 1;
	}
}

.input-area {
	background: #FFFFFF;
	border-top: 1px solid #E5E5E5;
	padding: 10px 15px;
	padding-bottom: calc(10px + env(safe-area-inset-bottom));
}

.input-container {
	display: flex;
	align-items: flex-end;
	gap: 10px;
}

.message-input {
	flex: 1;
	min-height: 40px;
	max-height: 120px;
	padding: 10px 15px;
	border: 1px solid #E5E5E5;
	border-radius: 20px;
	font-size: 16px;
	line-height: 1.4;
	background: #F8F9FA;
}

.send-btn {
	width: 60px;
	height: 40px;
	border-radius: 20px;
	background: #E5E5E5;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&.active {
		background: #007AFF;
		
		.send-text {
			color: #FFFFFF;
		}
	}
	
	.send-text {
		font-size: 14px;
		color: #999999;
		font-weight: 500;
	}
}

.menu-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.menu-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 40px;
	overflow: hidden;
}

.menu-option {
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
	
	.option-text {
		font-size: 16px;
		color: #333333;
	}
}

// 会话列表弹窗样式
.conversation-list-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.conversation-list-content {
	width: 90%;
	max-width: 400px;
	max-height: 70vh;
	background: #FFFFFF;
	border-radius: 12px;
	display: flex;
	flex-direction: column;
}

.conversation-list-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
	border-bottom: 1px solid #E5E5E5;

	.list-title {
		font-size: 18px;
		font-weight: 600;
		color: #333333;
	}

	.close-btn {
		font-size: 24px;
		color: #999999;
		cursor: pointer;
	}
}

.conversation-list-scroll {
	flex: 1;
	max-height: 400px;
}

.conversation-item {
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
	cursor: pointer;

	&:last-child {
		border-bottom: none;
	}

	&:active {
		background: #F8F9FA;
	}

	&.active {
		background: #E3F2FD;

		.conversation-title {
			color: #1976D2;
		}
	}
}

.conversation-info {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 5px;
}

.conversation-title {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.conversation-time {
	font-size: 12px;
	color: #999999;
}

.conversation-preview {
	.preview-text {
		font-size: 14px;
		color: #666666;
		line-height: 1.4;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}

.empty-conversations {
	padding: 40px 20px;
	text-align: center;

	.empty-text {
		font-size: 14px;
		color: #999999;
	}
}

.conversation-list-footer {
	padding: 15px 20px;
	border-top: 1px solid #E5E5E5;
}

.new-conversation-btn {
	width: 100%;
	height: 44px;
	background: #007AFF;
	color: #FFFFFF;
	border: none;
	border-radius: 8px;
	font-size: 16px;
	font-weight: 500;
}
</style>
